package com.example.yin.config;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;


public class CorsInterceptor extends HandlerInterceptorAdapter {

    @Override
//    Spring MVC 的跨域资源共享(CORS)拦截器实现，用于处理浏览器的跨域请求问题
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));//允许跨域请求的来源
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");//允许的HTTP方法：POST, GET, OPTIONS, DELETE
        response.setHeader("Access-Control-Max-Age", "3600");//预检请求(OPTIONS)的缓存时间(3600秒=1小时)
        response.setHeader("Access-Control-Allow-Headers", "x_requested_with,x-requested-with,Authorization,Content-Type,token");//允许的请求头：包括x_requested_with、x-requested-with、Authorization、Content-Type、token
        response.setHeader("Access-Control-Allow-Credentials", "true");//允许跨域请求携带cookie等凭证信息
        return true;
    }
}
